package org.je.io.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.je.cons.JCons;
import org.je.util.DynBuffer;

public class FileReader
{
	/**
	 * @param f
	 * @return content
	 */
	public static byte[] load(File f) {
		if (f == null)
			throw new NullPointerException("f-is-null");
		DynBuffer bf = new DynBuffer();
		InputStream in = null;
		try {
			in = new FileInputStream(f);
			byte[] tem = new byte[1024];
			int len;
			while( (len = in.read(tem)) > -1 ) {
				bf.append(tem ,0 ,len);
			}
			return bf.toArray();
		} catch (Exception ex) {
			throw new RuntimeException("read-file:" + f.getPath() + ", " + ex.getMessage());
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (Exception ex) {}
		}
	}

	/**
	 * @param path
	 * @return str
	 */
	public static String read2gbk(String path) {
		try {
			return new String(load(new File(path)),JCons.enc().gbk);
		} catch (UnsupportedEncodingException ex) {
			throw new RuntimeException(ex);
		}
	}

	/**
	 * @param path
	 * @return str
	 */
	public static String read2utf8(String path) {
		try {
			return new String(load(new File(path)),JCons.enc().utf8);
		} catch (UnsupportedEncodingException ex) {
			throw new RuntimeException(ex);
		}
	}

	/**
	 * @param path
	 * @return str
	 */
	public static String read2string(String path) {
		try {
			return new String(load(new File(path)),JCons.enc().os_charset);
		} catch (UnsupportedEncodingException ex) {
			throw new RuntimeException(ex);
		}
	}
}
